package com.feng.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.feng.model.StevenBill;
import com.feng.service.StevenService;
import com.feng.util.ExcelReader;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2017/9/3.
 */
@RestController
@RequestMapping(value = "/steven")
public class StevenAction {
    private static Logger log = LogManager.getLogger(StevenAction.class);


    @Autowired
    private StevenService stevenService;

    @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
    public JSONObject uploadExcelForSteven(@RequestParam("file") MultipartFile file,HttpSession session) {
        JSONObject ret = new JSONObject();
        boolean success = false;
        String curSheet = "";
        String curRow = "";
        try {
            InputStream ins =  file.getInputStream();
            Workbook wookbook = WorkbookFactory.create(ins);
            List<StevenBill> list = new ArrayList<StevenBill>();

            for(int sheetIndex =0;sheetIndex<wookbook.getNumberOfSheets();sheetIndex++){
                Sheet sheet = wookbook.getSheetAt(sheetIndex);
                String companyName = sheet.getSheetName();
                curSheet = "Sheet页："+companyName;
                Row firstRow = sheet.getRow(0);
                if(firstRow == null) continue;
                //台帐模式,一行中同时包含交强与商业保单号
                boolean excelTypeTotal = !ExcelReader.hasTitle(firstRow,"险别");
                if(excelTypeTotal){
                    stevenService.parseBillTotal(sheet,list);
                }else{
                    stevenService.parseBillBaosi(sheet, list);
                }
            }
            session.setAttribute("list",list);
            ret.put("list",list);
            success = true;
        } catch (Exception e) {
            ret.put("error", e.getMessage()+"</br>错误位置："+curSheet+"，</br>"+curRow);
            log.error(e.getMessage(),e);
        }
        ret.put("success",success);
        return ret;
    }

    @RequestMapping(value = "/getBills", method = RequestMethod.POST)
    public Collection getStevenBills(HttpSession session) {
        return (List)session.getAttribute("list");
    }

    @RequestMapping(value = "/compareExcel", method = RequestMethod.POST)
    public JSONObject compareExcelForSteven(@RequestParam("file") MultipartFile file,HttpServletResponse resp,HttpSession session) throws IOException {
        JSONObject ret = new JSONObject();
        InputStream ins = null;
        ServletOutputStream out = null;
        try {
            ins =  file.getInputStream();
            String oriName =file.getOriginalFilename();
            Workbook wookbook = WorkbookFactory.create(ins);

            stevenService.initStyle(wookbook);

            for(int sheetIndex =0;sheetIndex<wookbook.getNumberOfSheets();sheetIndex++){
                Sheet sheet = wookbook.getSheetAt(sheetIndex);
                String companyName = sheet.getSheetName();
                Row firstRow = sheet.getRow(0);
                if(firstRow == null) continue;
                //台帐模式,一行中同时包含交强与商业保单号
                boolean excelTypeTotal = !ExcelReader.hasTitle(firstRow,"险别");
                if(excelTypeTotal){
                    stevenService.compareBillTotal(sheet, (List) session.getAttribute("list"));
                }else{
                    stevenService.compareBillBaosi(sheet, (List) session.getAttribute("list"));
                }
            }

            resp.setContentType("application/octet-stream");
            //通知浏览器下载文件而不是打开
            String fileName =  java.net.URLEncoder.encode(ExcelReader.replaceLast(oriName, ".", "_比对结果."), "UTF-8");
            resp.addHeader("Content-Disposition", "attachment; filename="+fileName);
            out = resp.getOutputStream();
            wookbook.write(out);
        } catch (Exception e) {
            ret.put("error",e.getMessage());
            log.error(e.getMessage(),e);
        }finally {
            if(ins!=null)   ins.close();
            if(out !=null)   out.close();
        }
        return ret;
    }
}
